import time
import random
import string
from datetime import datetime

import pandas as pd
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QColor
from PyQt5.QtWidgets import QWidget
import os
from backEnd.database import DBOperation

from PyQt5.QtCore import QRegExp
from PyQt5.QtGui import QRegExpValidator


def generate_id(n=14):
    timestamp = int(time.time() * 1000)  # 当前时间戳（毫秒级）
    random_part = random.randint(10000000, 99999999)  # 生成8位随机数

    # 将时间戳和随机数拼接
    raw_id = str(timestamp) + str(random_part)

    # 将时间戳和随机数拼接成12位的ID
    id = raw_id[12:]
    return id


# 生成名称
def generate_random_name():
    # 百家姓数据
    chinese_surnames = ["赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈",
                        "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许",
                        "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏",
                        "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章",
                        "云", "苏", "潘", "葛", "奚", "范", "彭", "郎", "鲁", "韦",
                        "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳",
                        "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺",
                        "倪", "汤", "滕", "殷", "罗", "毕", "郝", "邬", "安", "常",
                        "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余",
                        "元", "卜", "顾", "孟", "平", "黄", "和", "穆", "萧", "尹"]
    name_type = random.choice(["Chinese", "English"])
    if name_type == "Chinese":
        surname = random.choice(chinese_surnames)
        given_name = random.choice(chinese_surnames)
        name = surname + given_name
    else:
        name_length = random.randint(4, 8)
        letters = string.ascii_lowercase
        first_letter = random.choice(string.ascii_uppercase)
        rest_letters = ''.join(random.choice(letters) for _ in range(name_length - 1))
        name = first_letter + rest_letters

    return name


# 非法字符检测
def contains_illegal_characters(password):
    illegal_characters = [' ', '\t', '\n', '#', '$', '%']

    for char in password:
        if char in illegal_characters:
            return True

    return False


def get_common_mysql_error(error):
    common_errors = {
        1045: "Access denied for user.",
        1146: "Table doesn't exist.",
        1062: "Duplicate entry.",
        1215: "Cannot add foreign key constraint.",
        1451: "Cannot delete or update a parent row: a foreign key constraint fails.",
        1452: "Cannot add or update a child row: a foreign key constraint fails.",
        2002: "Can't connect to MySQL server.",
        2006: "MySQL server has gone away.",
        2013: "Lost connection to MySQL server during query.",
        1064: "You have an error in your SQL syntax.",
        1114: "The table is full.",
        1265: "Data truncated for column.",
        1364: "Field doesn't have a default value.",
        1406: "Data too long for column.",
        1411: "Incorrect use of INSERT and SET.",
        1457: "Failed to load routine.",
        1690: "DOUBLE value is out of range.",
        1813: "Tablespace for table xxx exists.",
        1820: "You must reset your password.",
        # 添加其他常见错误和对应的描述
    }

    error = str(error)  # 将错误转换为字符串

    # 检查错误代码是否在常见错误字典中
    for code, description in common_errors.items():
        if str(code) in error:
            return description

    # 如果错误代码不在常见错误字典中，返回原始错误信息
    return error


def generate_history_id():
    current_time = int(time.time() * 1000)  # 获取当前时间戳（毫秒级）
    random_part = random.randint(10000, 99999)  # 生成一个随机的 5 位数
    time_based_id = str(current_time) + str(random_part)  # 拼接时间戳和随机数
    time_based_id = time_based_id[:12]  # 截取后 12 位
    return time_based_id


def insert_history(tablename, history):
    history_data = [{
        "id": generate_history_id(),
        "id_operator": int(history["id_operator"]),
        "name_operator": str(history["name_operator"]),
        "date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "operation": str(history["operation"]),
        "pass": int(history["pass"])
    }]
    print(history)
    print(pd.DataFrame(history_data))
    db = DBOperation.db_Operation()
    re, db_massage = db.insert(tablename, pd.DataFrame(history_data))
    return re, db_massage


def get_project_rootpath():
    # 获取当前脚本文件的绝对路径
    current_file = os.path.abspath(__file__)
    # 获取当前脚本所在的目录路径
    current_directory = os.path.dirname(current_file)
    # 获取项目根目录
    project_root = os.path.abspath(os.path.join(current_directory, os.pardir))
    print("项目根目录:", project_root)
    return project_root


if __name__ == "__main__":
    for i in range(10):
        print(generate_id())
